package flc.ast.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;

import android.app.Dialog;
import android.graphics.Color;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.PathUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.stark.ve.EditorHolder;
import com.stark.ve.core.IEditorListener;

import java.util.ArrayList;
import java.util.List;

import flc.ast.BaseAc;
import flc.ast.HomeActivity;
import flc.ast.R;
import flc.ast.adapter.FormatAdapter;
import flc.ast.adapter.FormatFblAdapter;
import flc.ast.bean.FormatBean;
import flc.ast.databinding.ActivityVideoFormatBinding;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.media.video.VideoFormat;
import stark.common.basic.utils.FileP2pUtil;
import stark.common.basic.utils.FileUtil;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.view.container.StkRecycleView;

public class VideoFormatActivity extends BaseAc<ActivityVideoFormatBinding> {

    public static String videoPath;
    private Dialog myFblDialog, myMlDialog, myZlDialog, myFormatDialog;
    private String selFormat = "", selFbl = "", selMl = "", selZl = "", newName = "";
    private FormatFblAdapter fblAdapter;
    private FormatAdapter formatAdapter, mlAdapter, zlAdapter;
    private List<FormatBean> fblList = new ArrayList<>();
    private List<FormatBean> formatList = new ArrayList<>();
    private List<FormatBean> mlList = new ArrayList<>();
    private List<FormatBean> zlList = new ArrayList<>();
    private int formatPosition, fblPosition = 0, mlPosition = 0, zlPosition = 0;
    private long videoLength;
    private Handler mHandler;
    private final Runnable mTaskUpdateTime = new Runnable() {
        @Override
        public void run() {
            mDataBinding.tvPlayLeft.setText(TimeUtil.getMmss(mDataBinding.videoView.getCurrentPosition()));
            mHandler.postDelayed(this, 500);
        }
    };

    @Override
    protected int onCreate() {
        return R.layout.activity_video_format;
    }

    @Override
    protected void initView() {
        mDataBinding.ivVideoformatBack.setOnClickListener(v -> onBackPressed());
        mDataBinding.ivPlayStart.setOnClickListener(this);
        mDataBinding.ivPlayFull.setOnClickListener(this);
        mDataBinding.ivVideoformatSave.setOnClickListener(this);
        mDataBinding.tvFormat.setOnClickListener(this);
        mDataBinding.tvFbl.setOnClickListener(this);
        mDataBinding.tvMl.setOnClickListener(this);
        mDataBinding.tvZl.setOnClickListener(this);
        //目标格式
        formatDialog();
        //分辨率
        fblDialog();
        //码率
        mlDialog();
        //帧率
        zlDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivPlayStart://播放
                if (mDataBinding.videoView.isPlaying()) {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.abofang);
                    mDataBinding.videoView.pause();
                } else {
                    mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
                    mDataBinding.videoView.start();
                    startTime();
                }
                break;
            case R.id.ivPlayFull://放大
                PlayActivity.videoUri = videoPath;
                startActivity(PlayActivity.class);
                break;
            case R.id.tvFormat://目标格式
                myFormatDialog.show();
                break;
            case R.id.tvFbl://分辨率
                myFblDialog.show();
                break;
            case R.id.tvMl://码率
                myMlDialog.show();
                break;
            case R.id.tvZl://帧率
                myZlDialog.show();
                break;
            case R.id.ivVideoformatSave://保存
                newName = mDataBinding.etFileName.getText().toString();
                startConv();
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == formatAdapter) {
            formatAdapter.getItem(formatPosition).setSelect(false);
            formatAdapter.notifyItemChanged(formatPosition);
            formatPosition = position;
            formatAdapter.getItem(position).setSelect(true);
            formatAdapter.notifyItemChanged(position);
            selFormat = formatAdapter.getItem(position).getStr();
            mDataBinding.tvFormat.setText(selFormat);
            mDataBinding.tvFormat.setTextColor(Color.parseColor("#000000"));
            myFormatDialog.dismiss();
        } else if (adapter == fblAdapter) {
            fblAdapter.getItem(fblPosition).setSelect(false);
            fblAdapter.notifyItemChanged(fblPosition);
            fblPosition = position;
            fblAdapter.getItem(position).setSelect(true);
            fblAdapter.notifyItemChanged(position);
            selFbl = fblAdapter.getItem(fblPosition).getStr();
            mDataBinding.tvFbl.setText(selFbl + "  " + fblAdapter.getItem(position).getStr2());
            mDataBinding.tvFbl.setTextColor(Color.parseColor("#000000"));
            myFblDialog.dismiss();
        } else if (adapter == mlAdapter) {
            mlAdapter.getItem(mlPosition).setSelect(false);
            mlAdapter.notifyItemChanged(mlPosition);
            mlPosition = position;
            mlAdapter.getItem(position).setSelect(true);
            mlAdapter.notifyItemChanged(position);
            selMl = mlAdapter.getItem(mlPosition).getStr();
            mDataBinding.tvMl.setText(selMl);
            mDataBinding.tvMl.setTextColor(Color.parseColor("#000000"));
            myMlDialog.dismiss();
        } else if (adapter == zlAdapter) {
            zlAdapter.getItem(zlPosition).setSelect(false);
            zlAdapter.notifyItemChanged(zlPosition);
            zlPosition = position;
            zlAdapter.getItem(position).setSelect(true);
            zlAdapter.notifyItemChanged(position);
            selZl = zlAdapter.getItem(zlPosition).getStr();
            mDataBinding.tvZl.setText(selZl);
            mDataBinding.tvZl.setTextColor(Color.parseColor("#000000"));
            myZlDialog.dismiss();
        }
    }

    @Override
    protected void initData() {
        if (TextUtils.isEmpty(videoPath)) return;
        videoLength = MediaUtil.getDuration(videoPath);
        //设置播放器
        setPlayer();
    }

    //设置播放器
    private void setPlayer() {
        mHandler = new Handler();
        mDataBinding.tvPlayLeft.setText("00:00");
        mDataBinding.tvPlayRight.setText(" / " + TimeUtil.getMmss(videoLength));
        mDataBinding.videoView.setVideoPath(videoPath);
        mDataBinding.videoView.seekTo(1);
        mDataBinding.videoView.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mediaPlayer) {
                mDataBinding.tvPlayLeft.setText("00:00");
                mDataBinding.ivPlayStart.setImageResource(R.drawable.abofang);
                mDataBinding.videoView.seekTo(1);
                stopTime();
            }
        });
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
        mDataBinding.videoView.start();
        startTime();
    }

    //开始转换(帧率无效，不管它)
    private void comVideo(int videoWidth, int videoHeight, int ml, String format) {

        EditorHolder.editor().videoCompress(videoPath, videoWidth, videoHeight, ml, new IEditorListener() {
            @Override
            public void onSuccess(String outFilePath) {
                mDataBinding.ivVideoformatSave.setEnabled(true);
                saveVideo(outFilePath, format);
            }

            @Override
            public void onFailure(String errMsg) {
                mDataBinding.ivVideoformatSave.setEnabled(true);
                ToastUtils.showShort(R.string.conv_def);
            }

            @Override
            public void onProgress(int progress) {
                showDialog(getString(R.string.format_ing) + progress + getString(R.string.unit_percent));
            }
        });
    }

    //保存视频
    private void saveVideo(String path, String format) {
        RxUtil.create(new RxUtil.Callback<String>() {
            @Override
            public void doBackground(ObservableEmitter<String> emitter) {
                String filePath = FileUtil.generateFilePath(Content.myTemp, format);
                FileUtils.copy(path, filePath);
                emitter.onNext(filePath);
            }

            @Override
            public void accept(String savePath) {
                dismissDialog();
                ToastUtils.showShort(getString(R.string.save_success));
                //重命名
                FileUtils.rename(savePath, newName + format);
                String newPath = PathUtils.getFilesPathExternalFirst() + Content.myTemp + "/" + newName + format;
                //保存到相册
                FileP2pUtil.copyPrivateVideoToPublic(mContext, newPath);
                startActivity(HomeActivity.class);
            }
        });
    }

    //开始转换
    private void startConv() {
        if (TextUtils.isEmpty(selFormat)) {
            ToastUtils.showShort(R.string.please_sel_format);
        } else if (TextUtils.isEmpty(newName)) {
            ToastUtils.showShort(R.string.please_input_name);
        } else if (TextUtils.isEmpty(selFbl)) {
            ToastUtils.showShort(R.string.please_sel_fbl);
        } else if (TextUtils.isEmpty(selMl)) {
            ToastUtils.showShort(R.string.please_sel_ml);
        } else if (TextUtils.isEmpty(selZl)) {
            ToastUtils.showShort(R.string.please_sel_zl);
        } else {
            mDataBinding.ivVideoformatSave.setEnabled(false);
            //整理参数
            int width = getWidth();
            int height = getHeight();
            int ml1 = getMl();
            String format = getFormat();
            comVideo(width, height, ml1, format);//修改参数其实就是压缩视频
        }
    }

    //根据选择的分辨率获取宽
    private int getWidth() {
        int width = 0;
        if (selFbl.equals(getString(R.string.fbl_arg1))) {
            width = 1920;
        } else if (selFbl.equals(getString(R.string.fbl_arg2))) {
            width = 1280;
        } else if (selFbl.equals(getString(R.string.fbl_arg3))) {
            width = 640;
        } else if (selFbl.equals(getString(R.string.fbl_arg4))) {
            width = 480;
        }
        return width;
    }

    //根据选择的分辨率获取高
    private int getHeight() {
        int height = 0;
        if (selFbl.equals(getString(R.string.fbl_arg1))) {
            height = 1080;
        } else if (selFbl.equals(getString(R.string.fbl_arg2))) {
            height = 720;
        } else if (selFbl.equals(getString(R.string.fbl_arg3))) {
            height = 480;
        } else if (selFbl.equals(getString(R.string.fbl_arg4))) {
            height = 360;
        }
        return height;
    }

    //根据选择的码率获取码率比例
    private int getMl() {
        int mBitrateScale = 0;
        if (selMl.equals(getString(R.string.ml_name4))) {
            mBitrateScale = 250 * 1024;
        } else if (selMl.equals(getString(R.string.ml_name3))) {
            mBitrateScale = 2000 * 1024;
        } else if (selMl.equals(getString(R.string.ml_name2))) {
            mBitrateScale = 5000 * 1024;
        } else if (selMl.equals(getString(R.string.ml_name1))) {
            mBitrateScale = 8000 * 1024;
        }
        return mBitrateScale;
    }

    //根据选择的格式获取格式后缀
    private String getFormat() {
        String format = VideoFormat.MP4.getSuffix();
        if (selFormat.equals(getString(R.string.video_format_mp4))) {
            format = VideoFormat.MP4.getSuffix();
        } else if (selFormat.equals(getString(R.string.video_format_avi))) {
            format = VideoFormat.AVI.getSuffix();
        } else if (selFormat.equals(getString(R.string.video_format_mkv))) {
            format = VideoFormat.MKV.getSuffix();
        } else if (selFormat.equals(getString(R.string.video_format_3gp))) {
            format = VideoFormat.THREE_GP.getSuffix();
        } else if (selFormat.equals(getString(R.string.video_format_mov))) {
            format = VideoFormat.MOV.getSuffix();
        }
        return format;
    }

    @Override
    protected void onStop() {
        super.onStop();
        stopTime();
    }

    @Override
    protected void onResume() {
        super.onResume();
        //直接播放视频
        mDataBinding.videoView.seekTo(1);
        mDataBinding.ivPlayStart.setImageResource(R.drawable.azant);
        mDataBinding.videoView.start();
        startTime();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        FileUtils.delete(PathUtils.getFilesPathExternalFirst() + Content.myTemp);
    }

    private void startTime() {
        mHandler.post(mTaskUpdateTime);
    }

    private void stopTime() {
        mHandler.removeCallbacks(mTaskUpdateTime);
    }

    //目标格式
    private void formatDialog() {
        myFormatDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_format, null);
        myFormatDialog.setContentView(inflate);
        myFormatDialog.setCancelable(true);
        Window dialogWindow = myFormatDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView title = inflate.findViewById(R.id.tvDialogFormatTitle);
        title.setText(getString(R.string.format_title));
        StkRecycleView recycleView = inflate.findViewById(R.id.rvDialogFormatList);
        recycleView.setLayoutManager(new GridLayoutManager(mContext, 3));
        formatAdapter = new FormatAdapter();
        recycleView.setAdapter(formatAdapter);
        formatList.add(new FormatBean(getString(R.string.video_format_mp4), false));
        formatList.add(new FormatBean(getString(R.string.video_format_avi), false));
        formatList.add(new FormatBean(getString(R.string.video_format_mkv), false));
        formatList.add(new FormatBean(getString(R.string.video_format_mov), false));
        formatList.add(new FormatBean(getString(R.string.video_format_3gp), false));
        formatAdapter.setList(formatList);
        formatAdapter.setOnItemClickListener(this);
    }

    //分辨率
    private void fblDialog() {
        myFblDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_fbl, null);
        myFblDialog.setContentView(inflate);
        myFblDialog.setCancelable(true);
        Window dialogWindow = myFblDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView title = inflate.findViewById(R.id.tvDialogFblTitle);
        title.setText(getString(R.string.fbl));
        StkRecycleView recycleView = inflate.findViewById(R.id.rvDialogFormatList);
        recycleView.setLayoutManager(new GridLayoutManager(mContext, 3));
        fblAdapter = new FormatFblAdapter();
        recycleView.setAdapter(fblAdapter);
        fblList.add(new FormatBean(getString(R.string.fbl_name1), getString(R.string.fbl_arg1), false));
        fblList.add(new FormatBean(getString(R.string.fbl_name2), getString(R.string.fbl_arg2), false));
        fblList.add(new FormatBean(getString(R.string.fbl_name3), getString(R.string.fbl_arg3), false));
        fblList.add(new FormatBean(getString(R.string.fbl_name4), getString(R.string.fbl_arg4), false));
        fblAdapter.setList(fblList);
        fblAdapter.setOnItemClickListener(this);
    }

    //码率
    private void mlDialog() {
        myMlDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_format, null);
        myMlDialog.setContentView(inflate);
        myMlDialog.setCancelable(true);
        Window dialogWindow = myMlDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView title = inflate.findViewById(R.id.tvDialogFormatTitle);
        title.setText(getString(R.string.ml));
        StkRecycleView recycleView = inflate.findViewById(R.id.rvDialogFormatList);
        recycleView.setLayoutManager(new GridLayoutManager(mContext, 3));
        mlAdapter = new FormatAdapter();
        recycleView.setAdapter(mlAdapter);
        mlList.add(new FormatBean(getString(R.string.ml_name1), false));
        mlList.add(new FormatBean(getString(R.string.ml_name2), false));
        mlList.add(new FormatBean(getString(R.string.ml_name3), false));
        mlList.add(new FormatBean(getString(R.string.ml_name4), false));
        mlAdapter.setList(mlList);
        mlAdapter.setOnItemClickListener(this);
    }

    //帧率
    private void zlDialog() {
        myZlDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_format, null);
        myZlDialog.setContentView(inflate);
        myZlDialog.setCancelable(true);
        Window dialogWindow = myZlDialog.getWindow();
        //设置Dialog从窗体底部弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        lp.y = 50;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        TextView title = inflate.findViewById(R.id.tvDialogFormatTitle);
        title.setText(getString(R.string.ml));
        StkRecycleView recycleView = inflate.findViewById(R.id.rvDialogFormatList);
        recycleView.setLayoutManager(new GridLayoutManager(mContext, 3));
        zlAdapter = new FormatAdapter();
        recycleView.setAdapter(zlAdapter);
        zlList.add(new FormatBean(getString(R.string.zl_name1), false));
        zlList.add(new FormatBean(getString(R.string.zl_name2), false));
        zlList.add(new FormatBean(getString(R.string.zl_name3), false));
        zlList.add(new FormatBean(getString(R.string.zl_name4), false));
        zlList.add(new FormatBean(getString(R.string.zl_name5), false));
        zlAdapter.setList(zlList);
        zlAdapter.setOnItemClickListener(this);
    }

}